package com.zxc.judgeservice.startegy;



import cn.hutool.json.JSONUtil;
import com.zxc.judgeservice.codesandbox.CodeSandbox;
import com.zxc.oj.model.codesandbox.JudgeInfo;
import com.zxc.oj.model.dto.question.JudgeCase;
import com.zxc.oj.model.dto.question.JudgeConfig;
import com.zxc.oj.model.entity.Question;
import com.zxc.oj.model.enums.JudgeInfoMesageEnum;

import java.util.List;
import java.util.Optional;

public class JavaJudgeStrategy implements JudgeStartegy {


    /**
     * 执行判题
     *
     * @param judgeContext
     * @return
     */
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {

        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        List<String> inputs = judgeContext.getInputs();
        List<String> outputs = judgeContext.getOutputs();
        Question question = judgeContext.getQuestion();
        List<JudgeCase> judgeCases = judgeContext.getJudgeCases();
        JudgeInfo judgeInfoResponse = new JudgeInfo();
        Long memory = Optional.ofNullable(judgeInfo.getMemory()).orElse(0L);
        Long time = Optional.ofNullable(judgeInfo.getTime()).orElse(0L);
        judgeInfoResponse.setMemory(memory);
        judgeInfoResponse.setTime(time);
        JudgeInfoMesageEnum infoMessageEnum = JudgeInfoMesageEnum.Accepted;
        if (inputs.size() != outputs.size()) {
            infoMessageEnum = JudgeInfoMesageEnum.Wrong_Answer;
            judgeInfoResponse.setMessage(infoMessageEnum.getValue());
            return judgeInfoResponse;
        }

        for (int i = 0; i < judgeCases.size(); i++) {
            JudgeCase judgeCase = judgeCases.get(i);
            if (!judgeCase.getOutput().equals(outputs.get(i))) {
                infoMessageEnum = JudgeInfoMesageEnum.Wrong_Answer;
                judgeInfoResponse.setMessage(infoMessageEnum.getValue());
                return judgeInfoResponse;
            }
        }

        String judgeConfigStr = question.getJudgeConfig();
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
        Long memoryLimit = judgeConfig.getMemoryLimit();
        Long timeLimit = judgeConfig.getTimeLimit();
        //java优化
        timeLimit -= 10000L;
        if (memory > memoryLimit) {
            infoMessageEnum = JudgeInfoMesageEnum.Memory_Limit_Exceeded;
        }
        if (time > timeLimit) {
            infoMessageEnum = JudgeInfoMesageEnum.Time_Limit_Exceeded;
        }

        judgeInfoResponse.setMessage(infoMessageEnum.getValue());
        return judgeInfoResponse;
    }
}
